<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="用户名：admin / user">
        <template #prefix>
          <el-icon class="el-input__icon"><i-ep-user /></el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" v-model="loginForm.password" placeholder="密码：123456" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon"><i-ep-lock /></el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button round @click="resetForm(loginFormRef)" size="large">重置</el-button>
    <el-button round @click="login(loginFormRef)" size="large" type="primary" :loading="loading"> 登录 </el-button>
  </div>
</template>

<script setup lang="ts">
import { ElForm, ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import { FullName, HomePath } from '@/config'

type FormInstance = InstanceType<typeof ElForm>

interface State {
  formLoading: boolean
}
const userStore = useUserStore()
const loginFormRef = ref<FormInstance>()
const router = useRouter()
const loginRules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})
const loading = ref(false)
const loginForm = reactive<any>({
  username: 'admin',
  password: '123456',
})
const state: State = reactive({
  formLoading: false,
})

const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return

  formEl.validate(async (valid: boolean) => {
    if (!valid) return

    userStore
      .login(loginForm)
      .then((res: any) => {
        if (!res) return

        const { redirect, ...othersQuery } = router.currentRoute.value.query
        router.push({
          path: (redirect as string) || HomePath,
          query: {
            ...othersQuery,
          },
        })

        ElNotification({
          message: `欢迎登录 ${FullName}`,
          type: 'success',
          duration: 3000,
        })
      })
      .catch((err: any) => {
        console.log('err', err)
        state.formLoading = true
      })
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped lang="scss">
@import './index.scss';
</style>
